import React, { useState, createContext, useEffect } from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import CheckConnect from "./Component/CheckConnect";
import Header from "./Component/Header";
import Main from "./Component/Main";
import Manager from "./Component/Manager";
import Profile from "./Component/Profile";
import SongWram from "./Component/SongWram";
import Details from "./Component/Details";
import { ethers } from "ethers";
import Forus from "./Component/Forus";
import Usdetails from "./Component/Usdetails";
import Creatforus from "./Component/Creatforus";
import ContactUs from "./Component/ContactUs";
import SearchResults from "./Component/SearchResults";
const { ethereum } = window;
const AppState = createContext();

function App() {
  const [Foundationcontract, setFoundationcontract] = useState();
  const [isWeb3Connected, setIsWeb3Connected] = useState(false);
  const [address, setAddresst] = useState();
  const [chainId, setChainId] = useState();
  const [isConnected, setIsConnected] = useState(false);


  useEffect(() => {
    const a = async () => {
      if (typeof window.ethereum !== "undefined") {
        const accounts = await ethereum.request({ method: "eth_accounts" });
        if (accounts.length > 0) {
          setAddresst(accounts[0]);
          setIsWeb3Connected(true);
        } else {
          console.log("没有找到账户信息");
        }
      } else {
        console.log("找不到以太坊提供商，安装 Metamask");
      }
    };

    if (!isWeb3Connected) {
      a();
    }
  }, [isWeb3Connected]);
  useEffect(() => {
    const loadEthereum = async () => {
      if (typeof window.ethereum !== "undefined") {
        const ContractAbi = [
          {
            "inputs": [],
            "stateMutability": "nonpayable",
            "type": "constructor"
          },
          {
            "stateMutability": "payable",
            "type": "fallback"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "",
                "type": "address"
              }
            ],
            "name": "contributors",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "contributorsNumber",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "string",
                "name": "_tittle",
                "type": "string"
              },
              {
                "internalType": "string",
                "name": "_description",
                "type": "string"
              },
              {
                "internalType": "address payable",
                "name": "_recipient",
                "type": "address"
              },
              {
                "internalType": "uint256",
                "name": "_targetMoney",
                "type": "uint256"
              },
              {
                "internalType": "string",
                "name": "_photo",
                "type": "string"
              }
            ],
            "name": "createAdminRequest",
            "outputs": [],
            "stateMutability": "nonpayable",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "string",
                "name": "_tittle",
                "type": "string"
              },
              {
                "internalType": "string",
                "name": "_description",
                "type": "string"
              },
              {
                "internalType": "uint256",
                "name": "_targetMoney",
                "type": "uint256"
              },
              {
                "internalType": "string",
                "name": "_photo",
                "type": "string"
              }
            ],
            "name": "createUserRequest",
            "outputs": [],
            "stateMutability": "nonpayable",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "_requestid",
                "type": "uint256"
              }
            ],
            "name": "executeRequest",
            "outputs": [],
            "stateMutability": "nonpayable",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "fixedRecipient",
            "outputs": [
              {
                "internalType": "address",
                "name": "",
                "type": "address"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "getBalance",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "_address",
                "type": "address"
              }
            ],
            "name": "getContributorAddresses",
            "outputs": [
              {
                "internalType": "address[]",
                "name": "",
                "type": "address[]"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "_address",
                "type": "address"
              }
            ],
            "name": "getContributorBalance",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "_address",
                "type": "address"
              }
            ],
            "name": "getContributorCompletedStatus",
            "outputs": [
              {
                "internalType": "bool[]",
                "name": "",
                "type": "bool[]"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "_address",
                "type": "address"
              }
            ],
            "name": "getContributorDescriptions",
            "outputs": [
              {
                "internalType": "string[]",
                "name": "",
                "type": "string[]"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "_address",
                "type": "address"
              }
            ],
            "name": "getContributorMoney",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "_address",
                "type": "address"
              }
            ],
            "name": "getContributorRequestIds",
            "outputs": [
              {
                "internalType": "uint256[]",
                "name": "",
                "type": "uint256[]"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "_address",
                "type": "address"
              }
            ],
            "name": "getContributorTargetAmounts",
            "outputs": [
              {
                "internalType": "uint256[]",
                "name": "",
                "type": "uint256[]"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "getContributorsNumber",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "_requestId",
                "type": "uint256"
              },
              {
                "internalType": "address",
                "name": "_donor",
                "type": "address"
              }
            ],
            "name": "getDonation",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              },
              {
                "internalType": "address",
                "name": "",
                "type": "address"
              },
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "_requestId",
                "type": "uint256"
              }
            ],
            "name": "getRequestDonations",
            "outputs": [
              {
                "internalType": "address[]",
                "name": "",
                "type": "address[]"
              },
              {
                "internalType": "uint256[]",
                "name": "",
                "type": "uint256[]"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "_requestid",
                "type": "uint256"
              }
            ],
            "name": "getRequestVoters",
            "outputs": [
              {
                "internalType": "address[]",
                "name": "",
                "type": "address[]"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "manager",
            "outputs": [
              {
                "internalType": "address",
                "name": "",
                "type": "address"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "minMoney",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "raisedAmount",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "name": "requestions",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "uniqueid",
                "type": "uint256"
              },
              {
                "internalType": "string",
                "name": "tittle",
                "type": "string"
              },
              {
                "internalType": "string",
                "name": "description",
                "type": "string"
              },
              {
                "internalType": "address payable",
                "name": "recipient",
                "type": "address"
              },
              {
                "internalType": "string",
                "name": "photo",
                "type": "string"
              },
              {
                "internalType": "uint256",
                "name": "targetMoney",
                "type": "uint256"
              },
              {
                "internalType": "uint256",
                "name": "raisedAmount",
                "type": "uint256"
              },
              {
                "internalType": "bool",
                "name": "completed",
                "type": "bool"
              },
              {
                "internalType": "uint256",
                "name": "votersNumber",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "requestsNumber",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "sendMoney",
            "outputs": [],
            "stateMutability": "payable",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "address",
                "name": "",
                "type": "address"
              }
            ],
            "name": "userDonors",
            "outputs": [
              {
                "internalType": "bool",
                "name": "",
                "type": "bool"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "userraisedAmount",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "name": "userrequestions",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "uniqueid",
                "type": "uint256"
              },
              {
                "internalType": "string",
                "name": "tittle",
                "type": "string"
              },
              {
                "internalType": "string",
                "name": "description",
                "type": "string"
              },
              {
                "internalType": "address payable",
                "name": "recipient",
                "type": "address"
              },
              {
                "internalType": "string",
                "name": "photo",
                "type": "string"
              },
              {
                "internalType": "uint256",
                "name": "targetMoney",
                "type": "uint256"
              },
              {
                "internalType": "uint256",
                "name": "userraisedAmount",
                "type": "uint256"
              },
              {
                "internalType": "bool",
                "name": "completed",
                "type": "bool"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [],
            "name": "userrequestsNumber",
            "outputs": [
              {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
              }
            ],
            "stateMutability": "view",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "_requestId",
                "type": "uint256"
              }
            ],
            "name": "usersendMoney",
            "outputs": [],
            "stateMutability": "payable",
            "type": "function"
          },
          {
            "inputs": [
              {
                "internalType": "uint256",
                "name": "_requestid",
                "type": "uint256"
              }
            ],
            "name": "voteRequest",
            "outputs": [],
            "stateMutability": "nonpayable",
            "type": "function"
          },
          {
            "stateMutability": "payable",
            "type": "receive"
          }
        ]
        const ContractAddress = "0x820250A3e145382745388733AFb938F040a4e694";
        const provider = new ethers.providers.Web3Provider(window.ethereum);
        const signer = provider.getSigner();
        const Foundationcontract = new ethers.Contract(
          ContractAddress,
          ContractAbi,
          signer
        );
        setFoundationcontract(Foundationcontract);
      } else {
        console.log("找不到以太坊提供商，安装metamask");
      }
    };
    if (!isWeb3Connected) {
      loadEthereum();
    }
  }, [isWeb3Connected]);
  useEffect(() => {
    const handleAccountsChanged = (accounts) => {
      setAddresst(accounts[0]);
    };

    const handleChainChanged = (chainId) => {
      if (chainId === "0xaa36a7") {
        setChainId(chainId);
        setIsConnected(true);
        alert("连接Sepolia 测试网络成功");
      } else {
        alert("请连接 Sepolia 测试网络");
      }
    };

    ethereum.on("accountsChanged", handleAccountsChanged);
    ethereum.on("chainChanged", handleChainChanged);

    return () => {
      ethereum.removeListener("accountsChanged", handleAccountsChanged);
      ethereum.removeListener("chainChanged", handleChainChanged);
    };
  }, [ethereum, isConnected]);
  return (
    <AppState.Provider
      value={{
        Foundationcontract,
      }}
    >
      <Router>
        <Routes>
          <Route path="/" element={<CheckConnect address={address} />} />
          <Route path="/header" element={<Header address={address} />}>
            <Route path="main" element={<Main address={address} />} />
            <Route path="manager" element={<Manager address={address} />} />
            <Route path="songwarm" element={<SongWram address={address} />} />
            <Route
              path="songwarm/:id"
              element={<Details address={address} />}
            />
            <Route path="profile" element={<Profile address={address} />} />
            <Route path="details" element={<Details address={address} />} />
            <Route path="forus" element={<Forus address={address} />} />
            <Route path="forus/:id" element={<Usdetails address={address} />} />
            <Route path="search" element={<SearchResults address={address} />} />
            <Route
              path="creatforus"
              element={<Creatforus address={address} />}
            />
          </Route>
        </Routes>
      </Router>
    </AppState.Provider>
  );
}

export default App;
export { AppState };
